package com.zeros.usercenter.ui.activity

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.zeros.baselibrary.ext.enable
import com.zeros.baselibrary.ext.onClick
import com.zeros.baselibrary.ui.activity.BaseMvpActivity
import com.zeros.usercenter.R
import com.zeros.usercenter.data.protocol.UserInfo
import com.zeros.usercenter.presenter.LoginPresenter
import com.zeros.usercenter.presenter.RegisterPresenter
import com.zeros.usercenter.presenter.view.LoginView
import com.zeros.usercenter.utils.UserPrefsUtils
import kotlinx.android.synthetic.main.activity_login.*
import org.jetbrains.anko.toast

/**
 * 登录界面
 */
class LoginActivity : BaseMvpActivity<LoginPresenter>(), View.OnClickListener, LoginView {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        mPresenter = LoginPresenter()//初始化Presenter
        mPresenter.mView = this   //初始化view,让此activity实现view
        initView()
    }

    /*初始化视图*/
    private fun initView() {
        mLoginBtn.enable(mMobileEt, { isBtnEnable() })
        mLoginBtn.enable(mPwdEt, { isBtnEnable() })

        mLoginBtn.onClick(this)
        //这是一位tabBar是其他布局的view所以需要getView
        mHeaderBar.getRightView().onClick(this)
        mForgetPwdTv.onClick(this)
    }

    override fun onClick(v: View) {
        when (v.id) {
        //跳转到注册界面
            R.id.mRightTv -> {
                val intent = Intent(this@LoginActivity, RegisterActivity::class.java)
                startActivity(intent)
            }
        //登录按钮
            R.id.mLoginBtn -> {
                mPresenter.login(mMobileEt.text.toString(), mPwdEt.text.toString(), "")
            }
        //忘记密码
            R.id.mForgetPwdTv -> {
                startActivity(Intent(this@LoginActivity, ForgetPwdActivity::class.java))
            }
        }
    }

    /*-判断输入是否为空-设置按钮是否可用-*/
    private fun isBtnEnable(): Boolean {
        return mMobileEt.text.isNullOrEmpty().not() &&
                mPwdEt.text.isNullOrEmpty().not()
    }


    /*-登录回调-*/
    override fun onLoginResult(result: UserInfo) {
        toast("登录成功")
        //登陆成功--保存所有信息
        UserPrefsUtils.putUserInfo(result)

        startActivity(Intent(this@LoginActivity, UserInfoActivity::class.java))
        finish()
    }

}
